package com.yitao.cms.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Function:
 * Date: 2019/1/9
 *
 * @author skipper
 * @desc
 * @see
 */
public class PropertyUtils {
    private static final Logger logger = LoggerFactory.getLogger(PropertyUtils.class);

    private static Properties props;

    static{
        loadProps();
    }

    synchronized static private void loadProps(){
        props = new Properties();
        InputStream in = null;
        String propertiesName = "application";
        String propertiesSuffix = ".yml";
        try {
            ClassLoader classLoader = PropertyUtils.class.getClassLoader();
            //先静态加载出主配置文件  查询出spring.profiles.active
            in = classLoader.getResourceAsStream(propertiesName + propertiesSuffix);
            props.load(in);
            String active = props.getProperty("spring.profiles.active");
            //getProperty 会出现取不到spring boot 格式的配置文件
            if(active == null){
                active = props.getProperty("active");
            }
            logger.info("预加载配置环境1:"+active+",加载的文件名"+propertiesName);
            if(active!=null && active!="prd"){
                String propertiesName2 = propertiesName + "-" + active + propertiesSuffix;
//                logger.info("预加载配置环境2:"+active+",加载的文件名"+propertiesName2);
                props.load(classLoader.getResourceAsStream(propertiesName2));
            }
        } catch (FileNotFoundException e) {
            logger.error("文件未找到");
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            try {
                if(null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("文件流关闭出现异常"+e);
            }
        }

    }

    public static String getProperty(String key){
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        if(null == props) {
            loadProps();
        }
        return props.getProperty(key, defaultValue);
    }
}
